package middleware

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"honeyweb/log"
	"honeyweb/model"
	"honeyweb/token"
	"net/http"
	"time"
)
var defaultJWT *token.JWT

func init() {
	defaultJWT = &token.JWT{
		SigningKey: []byte("hellobee"),
	}
}


func CreateAccountToken(uid int) string {
	claim := &model.CustomClaims{
		Uid: uid,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 1000,       // 签名生效时间
			ExpiresAt: time.Now().Unix() + 60*60*24*7, // 过期时间 7天
			Issuer:    "bee",                       // 签名的发行者
		},
	}
	str, _ := defaultJWT.CreateToken(claim)
	return str
}

func CheckToken(str string) (int, error) {
	claim , err := defaultJWT.ParseToken(str)
	if err != nil {
		return 0, err
	}
	return claim.Uid, nil
}


func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("token")
		if token == "" {
			log.S().Debug("not found token")
			//resp := model.NewErrJsonResp(0,"",model.E_BAD_PARAMS, "no token")
			//c.JSON(http.StatusOK,resp)
			//c.Abort()
			//TODO 后续要验证
			//c.Set("uid", 111)
			//log.S().Debug("set token uid:", 111)
			//c.Next()
			return
		}

		if uid, err := CheckToken(token); err != nil {
			log.S().Debug("err token:", token)
			resp := model.NewErrJsonResp(0,"",model.E_BAD_PARAMS, "no token")
			c.JSON(http.StatusOK,resp)
			c.Abort()
			return
		}else {
			c.Set("uid", uid)
			log.S().Debug(" token uid:", uid)
			c.Next()
		}
	}
}
